const {LinValidator, Rule} = require('../../core/lin-validator-v2')
const {User} = require('../models/user')
const {LoginType} = require('../lib/enum')

class PositiveIntegerValidator extends LinValidator {
  constructor () {
    super()
    this.id = [
      new Rule('isInt', '必须为正整数', {min: 1})
    ]
  }
}

class RegisterValidator extends LinValidator {
  constructor () {
    super()
    this.email = [
      new Rule('isEmail', '不符合Email规范')
    ]
    this.password1 = [
      new Rule('isLength', '密码最少6个字符，最多32个字符', {min:6, max:32}),
      // 指定密码范围 & 加强密码强度
      new Rule('matches', '密码不符合规范', '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]')
    ]
    this.password2 = this.password1
    this.nickname = [
      new Rule('isLength', '昵称最少4个字符，最多22个字符', {min:4, max:22}),
    ]
  }

  validatePasswrod (vals) {
    const pwd1 = vals.body.password1
    const pwd2 = vals.body.password2
    if(pwd1 !== pwd2) {
      throw Error('两次密码不一致')
    }
  }
  async validateEmail (vals) {
    const email = vals.body.email
    const user = await User.findOne({
      where: {
        email
      }
    })
    if(user) {
      throw new Error('email已经存在')
    }
  }
}

class TokenValidator extends LinValidator {
  constructor () {
    super()
    this.account = [
      new Rule('isLength', '不符合账号规则', {min: 4, max: 32})
    ]
    this.secret = [
      new Rule('isOptional'),
      new Rule('isLength', '至少6位字符', {min: 6, max: 32})
    ]
  }
  validateLoginType (vals) {
    if(!vals.body.type) {
      throw new Error('type是必须参数')
    }
    if(!LoginType.isThisType(vals.body.type)) {
      throw new Error('type参数不合法')
    }
  }
  validateWxLogin (vals) {
    if(vals.body.type === LoginType.USER_MINI_PROGRAM) {
      if(!vals.body.iv) {
        throw new Error('iv是必须参数')
      }
      if(!vals.body.encryptedData) {
        throw new Error('encryptedData是必须参数')
      }
    }
  }
}

class NotEmptyValidator extends LinValidator {
  constructor () {
    super()
    this.token = [
      new Rule('isLength', '不允许为空', {min: 1})
    ]
  }
}

module.exports = {
  PositiveIntegerValidator,
  RegisterValidator,
  TokenValidator,
  NotEmptyValidator
}